package com.dl.user.service.impl;


import com.dl.common.core.response.Result;
import com.dl.common.security.vo.TokenInfoVO;
import com.dl.user.dto.UserDTO;
import com.dl.user.entity.User;
import com.dl.user.mapper.UserMapper;
import com.dl.user.service.IUserService;
import com.dl.user.utils.JwtUtil;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements IUserService {


    @Resource
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper  userMapper;


    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public Result<String> register(User user) {
        //查询用户名石否已经存在
        if(userMapper.getUserByUsername(user.getUsername()) != null){
            return Result.error(400,"用户名已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.insert(user)  ? Result.success("注册成功") : Result.error("注册失败");
    }


    @Override
    public Result<TokenInfoVO> login(UserDTO user) {

        User realuser = userMapper.getUserByUsername(user.getUsername());
        //查询用户名是否存在
        if (realuser == null){
            return Result.error(400,"用户不存在");
        }
        if (!passwordEncoder.matches(user.getPassword(),realuser.getPassword())){
            return Result.error(400,"密码错误");
        }

        log.info("用户名密码正确");
        Long userId = realuser.getUserId();
        String role = realuser.getMajor();
        //生成token
        String token = jwtUtil.generateToken(user);
        TokenInfoVO tokenInfoVO = new TokenInfoVO();
        tokenInfoVO.setAccessToken(token);
        tokenInfoVO.setRefreshToken(token);
        tokenInfoVO.setExpireTime(jwtUtil.getExpiration());

        return Result.success(tokenInfoVO);
    }
}
